# -*- coding: utf-8 -*-
"""
心理咨询师服务系统 - 会员前台页面路由
"""

from flask import render_template, request, redirect, url_for, flash, current_app, session
from flask_jwt_extended import jwt_required, get_jwt_identity, verify_jwt_in_request
from app.members import bp
from app.models import User, UserMembership, Scale
from app import db


def get_current_user():
    """获取当前登录用户信息"""
    try:
        # 尝试验证JWT token
        verify_jwt_in_request(optional=True)
        user_id = get_jwt_identity()
        
        if user_id:
            user = User.get_by_id(user_id)
            if user and user.is_active:
                return user
    except Exception as e:
        current_app.logger.debug(f'获取用户信息失败: {str(e)}')
    
    # 开发环境下的临时解决方案：返回第一个用户用于测试
    if current_app.config.get('DEBUG', False):
        test_user = User.query.first()
        if test_user:
            return test_user
    
    return None


@bp.route('/login')
def login():
    """会员登录页面"""
    return render_template('members/login.html')


@bp.route('/register')
def register():
    """会员注册页面"""
    return render_template('members/register.html')


@bp.route('/dashboard')
def dashboard():
    """会员工作台概览"""
    # 获取当前用户信息
    user = get_current_user()
    
    # 临时简化统计数据
    stats = {
        'my_scales': 0,
        'total_assessments': 0, 
        'today_views': 0,
        'favorites': 0
    }
    
    # 暂时返回空数据
    recent_assessments = []
    my_scales = []
    
    return render_template('members/dashboard.html', 
                         user=user,
                         stats=stats,
                         recent_assessments=recent_assessments,
                         my_scales=my_scales)


@bp.route('/profile')
def profile():
    """个人资料页面"""
    user = get_current_user()
    return render_template('members/profile.html', user=user)


@bp.route('/plans')
def plans():
    """会员套餐页面"""
    user = get_current_user()
    return render_template('members/plans.html', user=user)


@bp.route('/my-scales')
def my_scales():
    """我的量表页面"""
    user = get_current_user()
    return render_template('members/my_scales.html', user=user, scales=None)


@bp.route('/scale-creator')
def scale_creator():
    """量表创建页面"""
    user = get_current_user()
    return render_template('members/scale_creator.html', user=user)


@bp.route('/scales/<int:scale_id>')
def scale_detail(scale_id):
    """会员量表详情页面"""
    user = get_current_user()
    return render_template('members/scale_detail.html', user=user, scale_id=scale_id)


@bp.route('/scale-library')
def scale_library():
    """量表库页面"""
    user = get_current_user()
    
    try:
        # 分页参数
        page = request.args.get('page', 1, type=int)
        per_page = 12
        category = request.args.get('category', '')
        search = request.args.get('search', '')
        
        # 构建查询
        query = Scale.query.filter_by(is_active=True)
        
        if category:
            query = query.filter_by(category=category)
        
        if search:
            query = query.filter(Scale.title.contains(search))
        
        # 分页查询
        scales = query.order_by(Scale.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        return render_template('members/scale_library.html', user=user, scales=scales, category=category, search=search)
    
    except Exception as e:
        current_app.logger.error(f'获取量表库失败: {str(e)}')
        flash('获取量表库失败，请稍后重试', 'error')
        return render_template('members/scale_library.html', user=user, scales=None, category='', search='')


@bp.route('/records')
def records():
    """测评记录页面"""
    user = get_current_user()
    return render_template('members/records.html', user=user, assessments=None)


@bp.route('/assessment-records')
def assessment_records():
    """专门的测评记录显示页面"""
    user = get_current_user()
    scale_id = request.args.get('scale_id')
    if not scale_id:
        flash('请指定量表ID', 'error')
        return redirect(url_for('members.records'))
    
    return render_template('members/assessment_records.html', user=user, scale_id=scale_id)


@bp.route('/analytics')
def analytics():
    """数据分析页面"""
    user = get_current_user()
    
    # 使用前端JavaScript处理认证和数据加载
    analytics_data = {
        'scales_count': 0,
        'assessments_count': 0,
        'monthly_stats': []
    }
    return render_template('members/analytics.html', user=user, analytics_data=analytics_data)


@bp.route('/scale-publications')
def scale_publications():
    """量表发布管理页面"""
    user = get_current_user()
    return render_template('members/scale_publications.html', user=user)


@bp.route('/publish-scale')
def publish_scale():
    """发布量表页面"""
    user = get_current_user()
    return render_template('members/publish_scale.html', user=user)


@bp.route('/publication-detail/<int:publication_id>')
def publication_detail(publication_id):
    """发布详情页面"""
    user = get_current_user()
    return render_template('members/publication_detail.html', user=user, publication_id=publication_id)